#include "Task.h"
#include <unistd.h>
#include <string>
#include <vector>
#include <cassert>
#include <iostream>
#include <ctime>
#include <sys/types.h>
#include <sys/wait.h>
#include "Task.h"

const int processnum = 10;
std::vector<func> tasks;

class channel
{
public:
    channel(int pipefd, pid_t processid, std::string &name)
        : _pipefd(pipefd), _processpid(processid), _processname(name)
    {
    }

public:
    int _pipefd;              // 管道文件描述符(写)
    pid_t _processpid;        // 子进程pid
    std::string _processname; // 子进程名字
};

void slaver()
{
    // read(0)
    int cmdcode = 0;
    while (true)
    {
        int n = read(0, &cmdcode, sizeof(int));
        if (n <= 0)
            break;
        if (n == sizeof(int))
        {
            // 执行cmd对应的任务列表
            std::cout << "slaver say@ get a commd : " << getpid() << ": cmdcode " << std::endl;
            // tasks[cmdcode]();
        }
    }
}

void InitProcessPool(std::vector<channel> *channels)
{
    // version2 确保每个子进程只有一个写端
    //  创建子进程
    std::vector<int> oldfds;
    for (int i = 0; i < processnum; ++i)
    {

        int pipefd[2] = {0};
        int n = pipe(pipefd);
        assert(!n);
        pid_t pid = fork();
        if (pid < 0)
            break;
        else if (pid == 0)
        {
            // 关闭曾经的写端
            std::cout << "child: " << getpid() << "close history fd :";
            for (auto &e : oldfds)
            {
                std::cout << " " << e;
                close(e);
            }
            std::cout << std::endl;
            // 子进程

            // 子进程读关闭写,描述符
            close(pipefd[1]);
            // 将读文件描述符重定向到标准输入
            dup2(pipefd[0], 0);
            close(pipefd[0]);
            // 执行任务
            slaver();
            // 子进程退出
            std::cerr << "process: " << getpid() << "  quit " << std::endl;
            exit(0);
        }

        // 父进程
        // 关闭读描述符
        close(pipefd[0]);

        // 初始化channel并添加到vector中去
        std::string name = std::string("processname") + std::to_string(i);
        channels->push_back(channel(pipefd[1], pid, name));
        oldfds.push_back(pipefd[1]);
        sleep(1);
    }
}

void Debug(const std::vector<channel> &channels)
{
    // 测试
    for (auto &e : channels)
    {
        std::cout << "pipfd: " << e._pipefd << "  processname: " << e._processname << " processid: " << e._processpid << std::endl;
    }

    sleep(500);
}

void ctrlSlaver(std::vector<channel> &channels)
{

    int which = 0;
    while (which < channels.size())
    {
        // 1.选择任务
        int cmdcode = random() % tasks.size();
        // 2.选择进程
        // int processpos = random() % channels.size();

        std::cout << "father say:" << "cmdcode" << "already sendto " << channels[which]._processpid << "  processname: " << channels[which]._processname << std::endl;
        // 3.发送任务
        write(channels[which]._pipefd, &cmdcode, sizeof(int));
        ++which;
        sleep(1);
    }
}

void QuitProcess(const std::vector<channel> &channels)
{

    // 写端并没有关完,子进程继承了上个子进程所有的写端
    //  for (const auto &e : channels)
    //      close(e._pipefd);

    // for (const auto &e : channels)
    //     waitpid(e._processpid, nullptr, 0);

    // 解决方案  version1
    for (int i = channels.size() - 1; i >= 0; --i)
    {
        close(channels[i]._pipefd);
        waitpid(channels[i]._processpid, nullptr, 0);
    }
}
int main()
{

    loadTask(&tasks);
    // 设置随机值
    srand(time(nullptr) ^ getpid() ^ 1023);

    // 组织好所有的channel
    std::vector<channel> channels;

    // 1. 初始化
    InitProcessPool(&channels);
    // Debug(channels);

    // 开始控制
    ctrlSlaver(channels);
    // 3.清理收尾
    QuitProcess(channels);

    return 0;
}